namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using System;
    using System.Data;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 产品逻辑删除 处理器
    /// </summary>
    public class ProductDeleteHandler : IRequestHandler<ProductDeleteCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepo;
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<ProductDeleteHandler> _logger;

        public ProductDeleteHandler(IBaseRepository<Product> productRepo, IDbConnectionFactory connectionFactory, ILogger<ProductDeleteHandler> logger)
        {
            _productRepo = productRepo;
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(ProductDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品Id无效", Data = 0 });

                // 使用同一连接 + 事务，确保全链路批量逻辑删除可回滚
                using var conn = _connectionFactory.CreateConnection();
                using var tran = conn.BeginTransaction();

                // 1) 校验产品是否存在且未删除
                using (var cmdCheck = conn.CreateCommand())
                {
                    cmdCheck.Transaction = tran;
                    cmdCheck.CommandText = "SELECT COUNT(1) FROM Product WHERE Id = @Id AND IsDeleted = 0";
                    var p = cmdCheck.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmdCheck.Parameters.Add(p);
                    var exists = Convert.ToInt32(cmdCheck.ExecuteScalar()) > 0;
                    if (!exists)
                    {
                        tran.Rollback();
                        return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品不存在或已删除", Data = 0 });
                    }
                }

                int affected = 0;

                // 2) 逻辑删除 Product
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Transaction = tran;
                    cmd.CommandText = "UPDATE Product SET IsDeleted = 1 WHERE Id = @Id AND IsDeleted = 0";
                    var p = cmd.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmd.Parameters.Add(p);
                    affected += cmd.ExecuteNonQuery();
                }

                // 3) 如果 Bom 存在 ProductId == @Id，则批量逻辑删除 Bom
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Transaction = tran;
                    cmd.CommandText = "UPDATE Bom SET IsDeleted = 1 WHERE ProductId = @Id AND IsDeleted = 0";
                    var p = cmd.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmd.Parameters.Add(p);
                    cmd.ExecuteNonQuery();
                }

                // 4) 如果 Bom 执行删除，则删除 BomItem（BomId in Bom where ProductId = @Id）
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Transaction = tran;
                    cmd.CommandText = @"UPDATE BomItem SET IsDeleted = 1 
                                        WHERE IsDeleted = 0 AND BomId IN (SELECT Id FROM Bom WHERE ProductId = @Id)";
                    var p = cmd.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmd.Parameters.Add(p);
                    cmd.ExecuteNonQuery();
                }

                // 5) 如果 Operation 存在 EquipmentId == @Id，则批量逻辑删除 Operation
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Transaction = tran;
                    cmd.CommandText = "UPDATE Operation SET IsDeleted = 1 WHERE EquipmentId = @Id AND IsDeleted = 0";
                    var p = cmd.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmd.Parameters.Add(p);
                    cmd.ExecuteNonQuery();
                }

                // 6) 如果 Bom 执行删除，则删除 ProcessRoute（BomId in Bom where ProductId = @Id）
                using (var cmd = conn.CreateCommand())
                {
                    cmd.Transaction = tran;
                    cmd.CommandText = @"UPDATE ProcessRoute SET IsDeleted = 1 
                                        WHERE IsDeleted = 0 AND BomId IN (SELECT Id FROM Bom WHERE ProductId = @Id)";
                    var p = cmd.CreateParameter();
                    p.ParameterName = "@Id";
                    p.Value = request.Id;
                    cmd.Parameters.Add(p);
                    cmd.ExecuteNonQuery();
                }

                tran.Commit();

                result.Code = APIEnums.Success;
                result.Msg = "删除产品成功";
                result.Data = affected; // 返回至少产品表影响行数
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("删除产品被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "删除产品异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "删除产品异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
